<template>
    <div style="margin-left: 50px">
        <!--搜索-->
        <el-row>
            <el-col :span="24">
                <div class="search">
                    <el-form :inline="true" :model="searchData" @keydown.enter.native="onSearch">
                        <el-form-item class="text" label="编号">
                            <el-input
                                    placeholder="请输入考试编号"
                                    v-model="searchData.id"
                                    size="small"
                                    clearable>
                            </el-input>
                        </el-form-item>
                        <el-form-item class="text" label="名称">
                            <el-input
                                    placeholder="请输入考试名称"
                                    v-model="searchData.examName"
                                    size="small"
                                    clearable>
                            </el-input>
                        </el-form-item>
                        <el-form-item class="text" label="科目">
                            <el-select v-model="searchData.examSubject"
                                       placeholder="请选择考试科目"
                                       size="small"
                                       clearable
                            >
                                <el-option
                                        v-for="item in examSubject"
                                        :key="item.id"
                                        :label="item.subject"
                                        :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item class="text" label="考场">
                            <el-input
                                    placeholder="请输入考试位置"
                                    v-model="searchData.examLocation"
                                    size="small"
                                    clearable>
                            </el-input>
                        </el-form-item>
                        <el-form-item class="text" label="考试状态">
                            <el-select v-model="searchData.examState"
                                       placeholder="请选择考试状态"
                                       clearable
                                       size="small"
                            >
                                <el-option
                                        v-for="item in examState"
                                        :key="item.valueId"
                                        :label="item.valueName"
                                        :value="item.valueId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button icon="el-icon-search" size="mini" type="primary" @click="onSearch">搜索</el-button>
                            <el-button icon="el-icon-refresh" size="mini" @click="onReset">重置</el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </el-col>
        </el-row>
        <!--工具栏-->
        <el-row>
            <el-col :span="24">
                <div class="tools">
                    <el-button @click="handleAddBtn" size="mini" icon="el-icon-plus" type="primary">新增</el-button>
                    <el-button :disabled="editBtnDisable" size="mini" icon="el-icon-edit"
                               @click="handleEditBtn(null,{id:selected[0]})"
                               type="success">修改
                    </el-button>
                    <el-button :disabled="deleteBtnDisable" size="mini" icon="el-icon-delete"
                               @click="handleDeleteByIds(selected)"
                               type="danger">删除
                    </el-button>
                    <el-button :loading="exportBtnLoading" :disabled="exportBtnDisable" size="mini"
                               icon="el-icon-download" type="warning" @click="exportRole">导出
                    </el-button>
                    <el-button :disabled="false" size="mini" icon="el-icon-refresh" @click="refresh">刷新
                    </el-button>
                </div>
            </el-col>
        </el-row>
        <!--表格-->
        <el-row>
            <el-col :span="24">
                <div style="width: auto;">
                    <el-table
                            :data="tableData"
                            row-key="id"
                            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                            @selection-change="selectionChange"
                            stripe
                            border
                            style="width: 100%;">
                        <el-table-column
                                type="selection"
                                align="center"
                                width="50">
                        </el-table-column>

                        <el-table-column
                                label="展开"
                                align="center"
                                type="expand"
                                width="50">
                            <template #default="props">
                                <el-form label-position="left" label-width="100px" inline class="demo-table-expand">
                                    <el-form-item label="考试编号：">
                                        <span>{{ props.row.id }}</span>
                                    </el-form-item>
                                    <el-form-item label="考试名称：">
                                        <span>{{ props.row.examName }}</span>
                                    </el-form-item>
                                    <el-form-item label="考试科目：">
                                <span
                                        v-for="item in examSubject"
                                        :key="item.id"
                                        :label="item.subject"
                                        :value="item.id"
                                        v-if="props.row.examSubject===item.id">
                                    {{item.subject}}
                                </span>
                                    </el-form-item>
                                    <el-form-item label="出卷人：">
                                        <span>{{ props.row.examProviderUser.name }}</span>
                                    </el-form-item>
                                    <el-form-item label="考试时间：">
                                        <span>
                                            {{ props.row.examBeginTime }}
                                            至
                                            {{ props.row.examOverTime }}
                                        </span>
                                    </el-form-item>
                                    <el-form-item label="考试时长：">
                                        <span>
                                            {{(new Date(props.row.examOverTime).getTime()-new Date(props.row.examBeginTime).getTime())/60000+'分钟'  }}
                                        </span>
                                    </el-form-item>
                                    <el-form-item label="考试地点：">
                                        <span>{{ props.row.examLocation }}</span>
                                    </el-form-item>
                                    <el-form-item label="考试状态：">
                                        <span
                                                v-for="item in examState"
                                                :key="item.valueId"
                                                :label="item.valueName"
                                                :value="item.valueId"
                                                v-if="props.row.examState===item.valueId">
                                    {{item.valueName}}
                                    </span>
                                    </el-form-item>
                                    <el-form-item label="考生数：">
                                        <span>{{ props.row.examJoinNum }}</span>
                                    </el-form-item>
                                </el-form>
                            </template>
                        </el-table-column>

                        <el-table-column
                                prop="examName"
                                align="left"
                                label="考试名称">
                        </el-table-column>
                        <el-table-column
                                align="left"
                                label="考试科目">
                            <template slot-scope="scope">
                                <span
                                        v-for="item in examSubject"
                                        :key="item.id"
                                        :label="item.subject"
                                        :value="item.id"
                                        v-if="scope.row.examSubject===item.id">
                                    {{item.subject}}
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column
                                prop="examProviderUser.name"
                                align="left"
                                label="出卷人"
                                width="160px">
                        </el-table-column>
                        <el-table-column
                                prop="examBeginTime"
                                align="left"
                                label="考试时间"
                                width="160px">
                        </el-table-column>
                        <el-table-column label="考试状态" width="100" align="center">
                            <template slot-scope="scope">
                                  <span
                                          v-for="item in examState"
                                          :key="item.valueId"
                                          :label="item.valueName"
                                          :value="item.valueId"
                                          v-if="scope.row.examState===item.valueId">
                                        <el-tag v-if="item.valueId===1">{{item.valueName}}</el-tag>
                                        <el-tag v-if="item.valueId===2" type="info">{{item.valueName}}</el-tag>
                                        <el-tag v-if="item.valueId===3" type="danger">{{item.valueName}}</el-tag>
                                        <el-tag v-if="item.valueId===4" type="warning">{{item.valueName}}</el-tag>
                                        <el-tag v-if="item.valueId===5" type="success">{{item.valueName}}</el-tag>
                                    </span>
                            </template>
                        </el-table-column>

                        <el-table-column
                                prop="examJoinNum"
                                width="100"
                                align="center"
                                label="考生数">
                        </el-table-column>
                        <el-table-column label="操作" align="center">
                            <template slot-scope="scope">
                                <el-button
                                        size="mini"
                                        type="text"
                                        icon="el-icon-edit"
                                        @click="handleEditBtn(scope.$index, scope.row)">编辑
                                </el-button>
                                <el-button
                                        size="mini"
                                        type="text"
                                        icon="el-icon-delete"
                                        @click="handleDeleteBtn(scope.$index, scope.row)">删除
                                </el-button>
                                &nbsp;
                                <el-dropdown size="mini">
                                    <el-button
                                            size="mini"
                                            type="text"
                                    >更多<i class="el-icon-arrow-down el-icon--right"></i>
                                    </el-button>
                                    <el-dropdown-menu size="medium" slot="dropdown">
                                        <el-dropdown-item @click.native="randomQuestions(scope.$index, scope.row)">
                                            <i class="el-icon-monitor"></i>随机抽题
                                        </el-dropdown-item>
                                        <el-dropdown-item @click.native="handleGetTestPaper(scope.$index, scope.row)">
                                            <i class="el-icon-document"></i>查看试卷
                                        </el-dropdown-item>
                                        <el-dropdown-item @click.native="handleInvigilate(scope.$index, scope.row)">
                                            <i class="el-icon-video-camera-solid"></i>智慧监考
                                        </el-dropdown-item>
                                        <el-dropdown-item @click.native="markingExamPapers(scope.$index, scope.row)">
                                            <i class="el-icon-view"></i>考试阅卷
                                        </el-dropdown-item>
                                        <el-dropdown-item @click.native="announceResults(scope.$index, scope.row)">
                                            <i class="el-icon-s-check"></i>公布成绩
                                        </el-dropdown-item>
                                    </el-dropdown-menu>
                                </el-dropdown>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div style="margin-top: 15px;text-align: right;">
                        <el-pagination
                                background
                                @size-change="handleSizeChange"
                                @current-change="handleCurrentChange"
                                :current-page="currentPage"
                                :page-sizes="[10,20,50,100, 200, 300, 400]"
                                :page-size="pageSize"
                                layout="total, sizes, prev, pager, next, jumper"
                                :total="total">
                        </el-pagination>
                    </div>
                </div>
            </el-col>
        </el-row>

        <el-dialog
                :close-on-click-modal="false"
                title="新增"
                width="600px"
                :visible.sync="addDialogVisible">
            <el-form :inline="false" :model="add"
                     label-position="right"
                     label-width="90px">
                <el-form-item class="text" label="考试名称">
                    <el-input
                            placeholder="请输入考试名称"
                            v-model="add.examName"
                            size="small"
                            clearable>
                    </el-input>
                </el-form-item>
                <el-form-item class="text" label="考试科目">
                    <el-select v-model="add.examSubject"
                               placeholder="请选择考试科目"
                               size="small"
                    >
                        <el-option
                                v-for="item in examSubject"
                                :key="item.id"
                                :label="item.subject"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item class="text" label="考试时间">
                    <el-date-picker
                            @change="timeChange"
                            v-model="time"
                            size="small"
                            type="datetimerange"
                            range-separator="至"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item class="text" label="考试地点">
                    <el-input
                            placeholder="请输入考试地点"
                            v-model="add.examLocation"
                            size="small"
                            clearable>
                    </el-input>
                </el-form-item>

            </el-form>

            <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="handleAdd">确 定</el-button>
  </span>
        </el-dialog>
        <el-dialog
                :close-on-click-modal="false"
                title="编辑"
                width="600px"
                :visible.sync="editDialogVisible"
        >
            <el-form :inline="false" :model="edit"
                     label-position="right"
                     label-width="90px">
                <el-form-item class="text" label="考试名称">
                    <el-input
                            placeholder="请输入考试名称"
                            v-model="edit.examName"
                            size="small"
                            clearable>
                    </el-input>
                </el-form-item>
                <el-form-item class="text" label="考试科目">
                    <el-select v-model="edit.examSubject"
                               placeholder="请选择考试科目"
                               size="small"
                    >
                        <el-option
                                v-for="item in examSubject"
                                :key="item.id"
                                :label="item.subject"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item class="text" label="考试时间">
                    <el-date-picker
                            @change="timeChange"
                            v-model="time"
                            size="small"
                            type="datetimerange"
                            range-separator="至"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item class="text" label="考试地点">
                    <el-input
                            placeholder="请输入考试地点"
                            v-model="edit.examLocation"
                            size="small"
                            clearable>
                    </el-input>
                </el-form-item>

            </el-form>
            <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="handleEdit">确 定</el-button>
  </span>
        </el-dialog>
        <!-- 随机抽题-->
        <el-dialog
                :close-on-click-modal="false"
                width="500px"
                title="随机抽题"
                :visible.sync="randomQuestionsDialogVisible"
        >
            <el-form :inline="true" :model="randomQuestionsParams"
                     label-position="right"
                     label-width="90px">
                <el-form-item class="text" label="关键字">
                    <el-input
                            placeholder="请输入关键字"
                            v-model="randomQuestionsParams.keyWord"
                            @input="searchCount"
                            size="small"
                            clearable>
                    </el-input>
                </el-form-item>

                <el-form-item class="text" label="单选题数">
                    <el-input-number v-model="randomQuestionsParams.singleChose"
                                     size="mini"
                                     :min="0"
                                     :max="searchCountData.singleChose"
                                     label="单选题数">
                    </el-input-number>
                </el-form-item>

                <el-form-item class="text" label="多选题数">
                    <el-input-number v-model="randomQuestionsParams.multipleChose"
                                     size="mini"
                                     :min="0"
                                     :max="searchCountData.multipleChose"
                                     label="多选题数">
                    </el-input-number>
                </el-form-item>
                <el-form-item class="text" label="填空题数">
                    <el-input-number v-model="randomQuestionsParams.fillBlanks"
                                     size="mini"
                                     :min="0"
                                     :max="searchCountData.fillBlanks"
                                     label="填空题数">
                    </el-input-number>
                </el-form-item>
                <el-form-item class="text" label="判断题数">
                    <el-input-number v-model="randomQuestionsParams.judge"
                                     size="mini"
                                     :min="0"
                                     :max="searchCountData.judge"
                                     label="判断题数">
                    </el-input-number>
                </el-form-item>
                <el-form-item class="text" label="主观题数">
                    <el-input-number v-model="randomQuestionsParams.subjective"
                                     size="mini"
                                     :min="0"
                                     :max="searchCountData.subjective"
                                     label="主观题数">
                    </el-input-number>
                </el-form-item>
                <div></div>
                <el-form-item>
                    <div style="font-size: 12px;color: #556cff;line-height: 2;padding: 5px 20px;">
                        搜索到相关题目共：<span style="color: #808080">{{searchCountData.total}}</span> 道题
                        <div></div>
                        单选：<span style="color: #808080">{{searchCountData.singleChose}}</span> 道，
                        多选：<span style="color: #808080">{{searchCountData.multipleChose}}</span> 道，
                        判断：<span style="color: #808080">{{searchCountData.judge}}</span> 道，
                        填空：<span style="color: #808080">{{searchCountData.fillBlanks}}</span> 道。
                        主观：<span style="color: #808080">{{searchCountData.subjective}}</span> 道。
                    </div>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
    <el-button @click="randomQuestionsDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="handleRandomQuestions">确 定</el-button>
  </span>
        </el-dialog>

    </div>
</template>

<script>
    import {onlyFormat} from "../../../../utils/date";
    import fileDownload from 'js-file-download';
    import {
        addExamination, announceResults,
        deleteExamination, deleteExaminationByIds,
        examinationList, exportExamination,
        getExaminationById, randomQuestions,
        updateExamination
    } from "../../../../api/examination";
    import {queryByTypeCode} from "../../../../api/dictionary";
    import {searchCount} from "../../../../api/questionBank";
    import {subjectDict} from "../../../../api/dictionary"

    export default {
        data() {
            return {
                searchData: {
                    id: "",
                    examName: "",
                    examSubject: "",
                    examLocation: "",
                    examState: "",
                },
                tableData: [],
                time: [],
                add: {
                    "examName": "",
                    "examSubject": "",
                    "examBeginTime": "",
                    "examOverTime": "",
                    "examLocation": "",
                },
                edit: {},
                total: 10,//总页数
                currentPage: 1,//当前页面
                pageSize: 10,//每页大小
                addDialogVisible: false,//显示添加模态框
                editDialogVisible: false,//显示修改模态框
                randomQuestionsDialogVisible: false,
                editBtnDisable: true,
                deleteBtnDisable: true,
                exportBtnDisable: true,
                exportBtnLoading: false,
                selected: [],
                examSubject: [],
                examState: [],
                searchCountData: {multipleChose: 0, total: 0, fillBlanks: 0, judge: 0, singleChose: 0, subjective: 0},
                randomQuestionsParams: {
                    id: "",
                    keyWord: "",
                    singleChose: 0,
                    multipleChose: 0,
                    fillBlanks: 0,
                    judge: 0,
                    subjective: 0
                },
            }
        },
        mounted() {
            this.initDict();
            this.getList()
        },
        methods: {
            //搜索
            async onSearch() {
                this.getList()
            },
            //搜索重置
            onReset() {
                this.searchData = {
                    id: "",
                    examName: "",
                    examSubject: "",
                    examLocation: "",
                    examState: "",
                };
                this.refresh()
            },
            //添加按钮
            handleAddBtn() {
                this.time = []
                Object.keys(this.add).forEach(key => {
                    this.add[key] = "";
                })
                this.addDialogVisible = true;
            },
            //刷新按钮
            refresh() {
                this.getList()
            },
            //编辑按钮
            async handleEditBtn(index, row) {
                this.time = []
                let resp = await getExaminationById(row.id)
                this.edit = resp.data
                this.editDialogVisible = true
                this.time.push(resp.data.examBeginTime)
                this.time.push(resp.data.examOverTime)
            },
            //随机出题
            async randomQuestions(index, row) {
                this.randomQuestionsParams.id = row.id;
                this.randomQuestionsParams.keyWord = "";
                this.searchCount()

                this.randomQuestionsParams.singleChose = 0;
                this.randomQuestionsParams.multipleChose = 0;
                this.randomQuestionsParams.fillBlanks = 0;
                this.randomQuestionsParams.judge = 0;
                this.randomQuestionsParams.subjective = 0;

                this.randomQuestionsDialogVisible = true
            }
            ,
            //提交编辑
            async handleEdit() {
                delete this.edit.examProviderUser
                delete this.edit.examProvider
                delete this.edit.examJoinNum
                delete this.edit.examState
                let resp = await updateExamination(this.edit)
                if (resp.code === 200) {
                    this.$message({
                        type: 'success',
                        message: '修改成功!'
                    });
                    this.refresh()
                    this.editDialogVisible = false
                } else {
                    this.$message({
                        type: 'error',
                        message: '修改失败：' + resp.message
                    });
                }
            }
            ,
            //删除按钮
            handleDeleteBtn(index, row) {
                this.$confirm('是否确认删除考试编号为"' + row.id + '"的数据项??', '警告', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    let resp = await deleteExamination(row.id)
                    if (resp.code === 200) {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.refresh();
                    } else {
                        this.$message({
                            type: 'error',
                            message: '删除失败！' + resp.message
                        });
                    }
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            }
            ,
            handleDeleteByIds() {
                this.$confirm('是否确认删除考试编号为"' + this.selected + '"的数据项??', '警告', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    let resp = await deleteExaminationByIds(this.selected)
                    if (resp.code === 200) {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.refresh();
                    } else {
                        this.$message({
                            type: 'error',
                            message: '删除失败：' + resp.message
                        });
                    }
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            }
            ,
            //获取列表
            async getList() {
                let resp = await examinationList(
                    this.searchData,
                    this.currentPage,
                    this.pageSize);
                this.total = resp.data.total;
                this.tableData = resp.data.list;
            },
            //获取列表
            getListPromise(fun) {
                examinationList(
                    this.searchData,
                    this.currentPage,
                    this.pageSize).then(resp => {
                    this.total = resp.data.total;
                    this.tableData = resp.data.list;
                    fun();
                })
            },

            //页数改变
            handleSizeChange(val) {
                this.pageSize = val
                this.refresh();
            }
            ,
            //翻页
            handleCurrentChange(val) {
                this.currentPage = val
                this.refresh();
            }
            ,

            async handleAdd() {
                let resp = await addExamination(this.add)
                if (resp.code === 200) {
                    this.$message.success('添加成功')
                    this.refresh();
                    this.addDialogVisible = false
                } else {
                    this.$message.error("添加失败：" + resp.message)
                }
            }
            ,
            selectionChange(selection) {
                if (selection.length === 0) {
                    this.editBtnDisable = true;
                    this.deleteBtnDisable = true;
                    this.exportBtnDisable = true;
                    this.selected.length = 0
                }

                if (selection.length > 0) {
                    this.deleteBtnDisable = false;
                    this.exportBtnDisable = false;
                    this.editBtnDisable = true;

                    this.selected.length = 0;
                    selection.forEach(item => {
                        this.selected.push(item.id)
                    })
                }
                if (selection.length === 1) {
                    this.editBtnDisable = false;
                }
            }
            ,
            async exportRole() {
                let data = await exportExamination(this.selected);
                fileDownload(data, "考试信息表.xlsx");
            }
            ,
            //解析时间
            parseDate(time) {
                return onlyFormat(time);
            }
            ,
            async initDict() {
                let resp = await subjectDict()
                this.examSubject = resp.data
                resp = await queryByTypeCode("exam_state")
                this.examState = resp.data

            }
            ,
            timeChange() {
                this.add.examBeginTime = this.parseDate(new Date(this.time[0]).getTime())
                this.add.examOverTime = this.parseDate(new Date(this.time[1]).getTime())
                this.edit.examBeginTime = this.parseDate(new Date(this.time[0]).getTime())
                this.edit.examOverTime = this.parseDate(new Date(this.time[1]).getTime())
            }
            ,
            async searchCount() {
                let resp = await searchCount(this.randomQuestionsParams.keyWord);
                this.searchCountData = resp.data
            }
            ,
            async handleRandomQuestions() {
                let resp = await randomQuestions(this.randomQuestionsParams)
                if (resp.code === 200) {
                    this.$message.success('电子试卷已生成')
                    this.refresh();
                    this.randomQuestionsDialogVisible = false
                } else {
                    this.$message.error("电子试卷失败：" + resp.message)
                }
            }
            ,
            async handleGetTestPaper(index, row) {
                if (row.examState === 1) {
                    this.$message.warning("请先命题")
                    return false;
                }
                await this.$router.push({
                    path: "/examination/testPaper",
                    query: {
                        id: row.id,
                    }
                })
            },
            handleInvigilate(i, row) {
                this.getListPromise(() => {
                    if (row.examState !== 3) {
                        this.$message.warning("只能监控状态为考试中的考室")
                        return false;
                    }
                    this.$router.push({
                        name: "Invigilate",
                        params: {
                            examInfo: row
                        },
                    })
                });
            },
            markingExamPapers(i, row) {
                this.getListPromise(() => {
                    if (row.examState !== 4) {
                        this.$message.warning("无法阅卷")
                        return false;
                    }
                    this.$router.push({
                        name: "MarkingExamPapers",
                        params: {
                            id: row.id
                        },
                    })
                });
            },
            announceResults(i, row) {
                this.$confirm('是否确公布成绩？?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'info'
                }).then(async () => {
                    let resp = await announceResults(row.id)
                    if (resp.code === 200) {
                        this.$message.success("已公布")
                        this.refresh();
                    } else {
                        this.$message.error("公布失败：" + resp.message)
                    }
                })
            }
        }
    }
</script>
<style scoped lang="scss">

    .demo-table-expand {
        margin: 0 auto;

        .el-form-item {
            width: 45%;
            text-align: left;
            margin: 0;
        }
    }
</style>